<?php
	require_once('databaseevent.class.php');
	require_once('configdatabase.class.php');
	require_once('databaseeventlist.class.php');
	require_once('lib/formatters/markdown-smartypants.php');
	
	$database = new ConfigDatabase();
	$eventList = new DatabaseEventList();
	$eventList->read($database->getConnection());
	
	header('Content-type: application/calendar+xml');
	
	$writer = new XMLWriter();
	$writer->openURI('php://output');
	$writer->startDocument('1.0');
	
	$writer->startElementNS('xCal', 'iCalendar', 'urn:ietf:params:xml:ns:xcal');
	
	$writer->startElement('vcalendar');
	$writer->writeElement('method', 'PUBLISH');
	$writer->writeElement('version', '2.0');
	$writer->writeElement('prodid', '-//der-kalender//NONSGML vGen v1.0//EN');

	foreach ($eventList as $event) {
		$writer->startElement('vevent');
		$writer->writeElement('uid', $event->getId() . '@der-kalender.' . $_SERVER['HTTP_HOST']);
		$writer->writeElement('summary', $event->getTitle());
		$writer->writeElement('dtstart', $event->getDateTime()->format('c'));
		$writer->startElement('description');
		$writer->writeCData(Markdown_SmartyPants($event->getDescription()));
		$writer->endElement();
		$writer->endElement();
	}
	
	$writer->endElement();
	$writer->endDocument();
	$writer->flush();